package com.example.floatdemoforuart;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cvte.tv.api.TvApiApplication;
import com.cvte.tv.api.TvServiceConnectListener;
import com.cvte.tv.api.aidl.EntityInputSource;
import com.cvte.tv.api.aidl.EnumInputStatus;
import com.cvte.tv.api.aidl.ITVApiSystemInputSourceAidl;
import com.cvte.tv.api.aidl.ITvApiManager;
import com.example.serialtest.SerialDataUtil;
import com.mstar.android.tv.TvCommonManager;
import com.mstar.android.tvapi.common.TvManager;
import com.mstar.android.tvapi.common.exception.TvCommonException;
import com.smart.mcuservice.ISmartMcuService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
	public static final int HDMI_SWITCH_HDMI1 = 0;
	public static final int HDMI_SWITCH_HDMI2 = 3;
	public static final int HDMI_SWITCH_DP = 1;
	private static final int MSG_UPDATE_USB_TEXT = 0;
	private static final String STORAGE_EXTERNAL = "/mnt/usb/";
	private static final int SOURCE_VGA = 0;
	private static final int SOURCE_HDMI1 = 1;
	private static final int SOURCE_DP = 2;
	private static final int SOURCE_CN8_HDMI = 3;
	private static final int SOURCE_PC_HDMI = 4;
	private static final int SOURCE_ANDROID_HDMI = 5;
	private static final String SHAREDPREFERENCE = "Data";
	private static final String CURRENT_SOURCE = "source";
	private static final int MSG_API_INIT_OK = 0;
	private SharedPreferences mSharedPreferences = null;
	private SharedPreferences.Editor mEditor = null;
	private TvCommonManager mTvCommonManager = null;
	private ITVApiSystemInputSourceAidl mSourceApi = null;
	private List<EntityInputSource> mSourceList = null;
	private List<Integer> idList = null;
	private TvManager tvManager = null;
	private Context context = null;
	private TextView usbCountText = null;
	private ISmartMcuService mService = null;
	private ServiceConnection conn=new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mService=null;
			Log.d("wuguitong","onServiceDisconnected");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mService=ISmartMcuService.Stub.asInterface(service);
			Log.d("wuguitong","onServiceConnected");
		}
	};
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_API_INIT_OK:
					initSource();
					break;
			}
		}
	};
	private void initSource() {
		if(mSourceApi == null)
			return;
		try {
			switch (mSharedPreferences.getInt(CURRENT_SOURCE, SOURCE_VGA)) {
				case SOURCE_VGA:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(0));
					break;
				case SOURCE_HDMI1:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_HDMI1);
					break;
				case SOURCE_DP:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_DP);
					break;
				case SOURCE_CN8_HDMI:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_HDMI2);
					break;
				case SOURCE_PC_HDMI:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(2));
					break;
				case SOURCE_ANDROID_HDMI:
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(3));
					break;
				default:
					break;
			}
		}catch (RemoteException e) {
			e.printStackTrace();
		} catch (TvCommonException e) {
			e.printStackTrace();
		}
	}
	@Override
	protected void onStart() {
		super.onStart();
		initSource();
	}

	@Override
	protected void onStop() {
		mTvCommonManager.setInputSource(TvCommonManager.INPUT_SOURCE_STORAGE);
		super.onStop();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_main);
		idList = new ArrayList<>();
		tvManager = TvManager.getInstance();
		mTvCommonManager = TvCommonManager.getInstance();
		mSharedPreferences = getSharedPreferences(SHAREDPREFERENCE, Context.MODE_PRIVATE);
		mEditor = mSharedPreferences.edit();
		TvApiApplication.getTvApi(new TvServiceConnectListener() {
			@Override
			public void OnConnected(ITvApiManager iTvApiManager) {
				try {
					mSourceApi = iTvApiManager.getTVApiSystemInputSource();
					mSourceList = mSourceApi.eventSystemInputSourceGetList();
					for (int i = 0; i < mSourceList.size(); i++) {
						if (mSourceList.get(i).status == EnumInputStatus.INPUT_STATUS_HIDE)
							continue;
						idList.add(new Integer(mSourceList.get(i).id));
					}
					mHandler.sendEmptyMessage(MSG_API_INIT_OK);

				} catch (RemoteException e) {
					e.printStackTrace();
				}

			}
		});
		Intent intent=new Intent("android.smart.uartservice.action.SMARTMCUSERVICE");
		bindService(intent, conn,BIND_AUTO_CREATE);
		Button ms828Usb = (Button) findViewById(R.id.ACT_MS828_USB);


		//source
		Button sourceVga = (Button)findViewById(R.id.ACT_SOURCE_VGA);
		Button sourceHdmi1Hdmi1 = (Button)findViewById(R.id.ACT_SOURCE_HDMI1_HDMI1);
		Button sourceHdmi1Hdmi2 = (Button)findViewById(R.id.ACT_SOURCE_HDMI1_HDMI2);
		Button sourceHdmi1Dp = (Button)findViewById(R.id.ACT_SOURCE_HDMI1_DP);
		Button sourceHdmi2Pc = (Button)findViewById(R.id.ACT_SOURCE_HDMI2_PC);
		Button sourceHdmi3Android = (Button)findViewById(R.id.ACT_SOURCE_HDMI3_ANDROID);
		Button setAllGpiohigh = (Button)findViewById(R.id.ACT_SET_ALL_GPIO_HIGH);
		Button setAllGpioLow = (Button)findViewById(R.id.ACT_SET_ALL_GPIO_LOW);
		Button testUart = (Button)findViewById(R.id.ACT_TEST_UART);
		Button setExtVgaEdid = (Button)findViewById(R.id.ACT_SET_EXT_VGA_EDID);
		Button testNetPortJ12 = (Button)findViewById(R.id.ACT_TEST_NET_PORT_J12);
		Button testNetPortJ13 = (Button)findViewById(R.id.ACT_TEST_NET_PORT_J13);

		ms828Usb.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"USB CHANGE",Toast.LENGTH_SHORT).show();
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
				}else {
					try {
						mService.setUsbSwitch(SerialDataUtil.SWITCH_MS828_USB);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
		});

		//source

		sourceVga.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					if(mService == null) {
						Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					}else {
						try {
							mService.setUsbSwitch(SerialDataUtil.SWITCH_J5_VGA_USB);
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(0));
					mEditor.putInt(CURRENT_SOURCE, SOURCE_VGA);
					mEditor.commit();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		sourceHdmi1Hdmi1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					if(mService == null) {
						Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					}else {
						try {
							mService.setUsbSwitch(SerialDataUtil.SWITCH_J7_HDMI_USB);
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_HDMI1);
					mEditor.putInt(CURRENT_SOURCE, SOURCE_HDMI1);
					mEditor.commit();
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (TvCommonException e) {
					e.printStackTrace();
				}
			}
		});
		sourceHdmi1Hdmi2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					if(mService == null) {
						Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					}else {
						try {
							mService.setUsbSwitch(SerialDataUtil.SWITCH_CN8_HDMI_USB);
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_HDMI2);
					mEditor.putInt(CURRENT_SOURCE, SOURCE_CN8_HDMI);
					mEditor.commit();
				} catch (TvCommonException e) {
					e.printStackTrace();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		sourceHdmi1Dp.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					if(mService == null) {
						Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					}else {
						try {
							mService.setUsbSwitch(SerialDataUtil.SWITCH_J9_DP_USB);
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(1));
					tvManager.setHdmiSwitchPort(HDMI_SWITCH_DP);
					mEditor.putInt(CURRENT_SOURCE, SOURCE_DP);
					mEditor.commit();
				} catch (TvCommonException e) {
					e.printStackTrace();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		sourceHdmi2Pc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					if(mService == null) {
						Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					}else {
						try {
							mService.setUsbSwitch(SerialDataUtil.SWITCH_CN7_PC_USB);
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(2));
					mEditor.putInt(CURRENT_SOURCE,SOURCE_PC_HDMI);
					mEditor.commit();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		sourceHdmi3Android.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Toast.makeText(context,"SOURCE CHANGE",Toast.LENGTH_SHORT).show();
				try {
					mSourceApi.eventSystemInputSourceSetInputSource(idList.get(3));
					mEditor.putInt(CURRENT_SOURCE,SOURCE_ANDROID_HDMI);
					mEditor.commit();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		setAllGpiohigh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					return;
				}
				try {
					boolean ret = mService.setGpioStatus((byte) 0x7f, true);
					if(ret){
						Toast.makeText(context, "Set Gpio High Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Set Gpio High Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		setAllGpioLow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					return;
				}
				try {
					boolean ret = mService.setGpioStatus((byte)0x7f,false);
					if(ret){
						Toast.makeText(context, "Set Gpio Low Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Set Gpio Low Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		testUart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					return;
				}
				try {
					boolean ret = mService.testMcuUart();
					if(ret){
						Toast.makeText(context, "Test Uart Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Test Uart Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		setExtVgaEdid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				try {
					boolean ret = TvManager.getInstance().setTvosInterfaceCommand("SetExtVgaEDID 00:00");
					if(ret){
						Toast.makeText(context, "Set EXT VGA EDID Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Set EXT VGA EDID Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (TvCommonException e) {
					e.printStackTrace();
				}
			}
		});
		testNetPortJ12.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					return;
				}
				try {
					boolean ret = mService.testNetPort(0);
					if(ret){
						Toast.makeText(context, "Test Net Port J12 Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Test Net Port J12 Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		testNetPortJ13.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				if(mService == null) {
					Toast.makeText(context, "Not Smart Mcu Service", Toast.LENGTH_SHORT).show();
					return;
				}
				try {
					boolean ret = mService.testNetPort(1);
					if(ret){
						Toast.makeText(context, "Test Net Port J13 Success!", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(context, "Test Net Port J13 Fail!", Toast.LENGTH_SHORT).show();
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		sourceVga.setFocusable(true);
		sourceVga.requestFocus();
		switch (mSharedPreferences.getInt(CURRENT_SOURCE, SOURCE_VGA)) {
			case SOURCE_VGA:
				sourceVga.requestFocus();
				break;
			case SOURCE_HDMI1:
				sourceHdmi1Hdmi1.requestFocus();
				break;
			case SOURCE_DP:
				sourceHdmi1Dp.requestFocus();
				break;
			case SOURCE_CN8_HDMI:
				sourceHdmi1Hdmi2.requestFocus();
				break;
			case SOURCE_PC_HDMI:
				sourceHdmi2Pc.requestFocus();
				break;
			case SOURCE_ANDROID_HDMI:
				sourceHdmi3Android.requestFocus();
				break;
			default:
				break;
		}

		usbCountText = (TextView)findViewById(R.id.USB_COUNT_TEXT);
		usbCountText.setText(String.valueOf(getMountPathList().size()));


		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
		intentFilter.setPriority(1000);
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
		intentFilter.addDataScheme("file");
		registerReceiver(broadcastRec, intentFilter);
	}
	public List<String> getMountPathList() {
		List<String> filepath = new ArrayList<>();

		// scan the usb or ext_sdcard , they all mount on /mnt/usb
		String[] scanList = {STORAGE_EXTERNAL,};
		for (String dir : scanList) {
			File rootFile = new File(dir);
			if (rootFile != null && rootFile.exists()) {
				for (File file : rootFile.listFiles()) {
					if (file.isDirectory() && (file.canRead() || file.canWrite())) {
						filepath.add(file.getPath());
					}
				}
			}
		}
		return filepath;
	}
	private final BroadcastReceiver broadcastRec = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d("wuguitong", "broadcase" + action);
			if (action.equals(Intent.ACTION_MEDIA_REMOVED) || action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_EJECT))
			{
				handler.sendEmptyMessage(MSG_UPDATE_USB_TEXT);
			}
		}
	};
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			//获得通过handler.sendEmptyMessage发送的消息编码
			int what = msg.what;
			switch (what) {
				case MSG_UPDATE_USB_TEXT:
					usbCountText.setText(String.valueOf(getMountPathList().size()));
					break;
				default:
					break;
			}
		}
	};
}
